<?php

namespace App\Http\Controllers\Admin;

use DB;
use App\Http\Controllers\Controller;
use App\Models\Area;
use App\Models\PriDeviceInfo;
use App\Http\Traits\UserPrivilege;
use Illuminate\Http\Request;
use App\Http\Traits\Utils;

class IndexController extends Controller
{
    use UserPrivilege, Utils;
    
    public function __construct() {

    }

    /**
     * 后台首页
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        
        //大棚数量
        $peng = Area::select(['AreaId', 'AreaName', 'Fid'])
                ->get()
                ->toArray();
        $province = [];
        $city = [];
        foreach ($peng as $v) {
            if ($v['Fid'] == 0) {
                $province[$v['AreaId']] = ['aid' => $v['AreaId'], 'label' => str_replace('省', '', $v['AreaName']) ];
            } else {
                $city[$v['Fid']] = isset($city[$v['Fid']])? $city[$v['Fid']] + 1 : 1;
            }
        }
        $dpTotal = array_sum($city);
        
        foreach ($province as $k => $v) {
            $province[$k]['num'] = isset($city[$k])?$city[$k]:0;
        }
        $dapeng = [];
        $dapengNum = array_values($province);
        foreach ($dapengNum as  $v) {
            $key = $v['label'];
            if(isset($dapeng[$key])) {
                $dapeng[$key] = ['aid'=> array_get($dapeng, $key.'.aid').', '.$v['aid'], 'label'=>$key, 'num'=>array_get($dapeng, $key.'.num') + $v['num']];
            }else{
                $dapeng[$key] = $v;
            }
        }
        $dapeng = array_values($dapeng);
        //设备数量
        $deviceTotal = PriDeviceInfo::count();
        //告警数量
        $warnsList = PriDeviceInfo::join('t_phpwarn', 't_prideviceinfo.pdi_index', '=', 't_phpwarn.pdi_devid')
                ->select('pdi_warnlevel', DB::raw('count("t_phpwarn.pdi_index") as num'))
                ->groupBy('pdi_warnlevel')->get();
        
        $warnDesc = config('device.warn_level');
        
        $warns = [];
        $warnTotal = 0;
        if($warnsList) {
            $warnNum = $warnsList->pluck('num', 'pdi_warnlevel')->all();
           
            $warnTotal = array_sum($warnNum);
            foreach ($warnDesc as $k => $v) {
                $warns[]=[ 'lvl'=>$v['name'], 'num'=>isset($warnNum[$k])?$warnNum[$k]:0, 'plvl'=>$k ];
            }
        }
        return $this->success('', compact('dpTotal', 'deviceTotal', 'warnTotal', 'warns', 'dapeng'));
    }
    
    
    /**
     * 检查版本更新
    */
    public function checkUpdate(Request $request) {
        $post = $request->input();
        $version = array_get($post, 'version', 0);
        $appType = array_get($post, 'app_type', 0);
        $appPhoneOs = strtolower(array_get($post, 'app_phone', 0));
        $config = collect(config('site.app_phone'))->pluck('value', 'label')->all();
        
        $user = $request->user();
        $cid = null;
        if($user) {
            $cid = $user->Co_ID;
        }
                
        $info = \App\Models\Apk::where([
            'app_status'=>1,
            'app_type'=>$appType,
            'app_phone'=> array_get($config, $appPhoneOs, '')
        ])
        ->where('app_version', '<>',  $version)
        ->where(function ($query) use($cid){
            return $query->where('company_id', 0)->orWhere('company_id', $cid);
        })
        ->orderBy('updated_at', 'desc')
        ->first();

        $url = '';
        if($info) {
          $newVersion = str_replace('.', '', $info->app_version);
          $reqVersion = str_replace('.', '', $version);
          if($reqVersion < $newVersion) {
            $url = $info->app_http?$info->app_http:$info->app_path;
          }else{
            $url = '';  
          }   
        }
        
        $data = [
            'apk' => $url,
        ];
        return $this->success('', $data);
    }
    
}
